by Manas Tungare (1 Submission)
Category: Files/File Controls/Input/Output
Compatability: Visual Basic 3.0
Difficulty: Intermediate
Date Added: Wed 3rd February 2021
Rating: (4 Votes)
A reusable function that computes the relative path of a file with respect to a given directory
Examples will make the point clear, so here goes:
GetRelativePath ("C:\VB\", "C:\VB\File.ext")
returns "File.ext"GetRelativePath ("C:\VB\", "C:\VB\Program\File.ext")
returns "Program\File.ext"GetRelativePath ("C:\VB\", "C:\File.ext")
returns "..\File.ext"
It is useful to insert images and hyperlinks into webpages, given the filenames of the images and the HTML file.
Inputs
sBase
Fully Qualified Path of the Base Directory
sFile
Fully Qualified Path of the File of which the relative path is to be computed.
GetRelativePath ("C:\VB\", CommonDialog1.Filename)
Relative Path of sFile with respect to sBase.
None.
Public Function GetRelativePath(sBase As String, sFile As String)
'------------------------------------------------------------
' Accepts : sBase= Fully Qualified Path of the Base Directory
' sFile= Fully Qualified Path of the File of which
' the relative path is to be computed.
' Returns : Relative Path of sFile with respect to sBase.
' Modifies: Nothing.
'------------------------------------------------------------
' Author : Manas Tungare (www.manastungare.com)
'------------------------------------------------------------
Dim Base() As String, File() As String
Dim I As Integer, NewTreeStart As Long, sRel As String
If Left(sBase, 3) <> Left(sFile, 3) Then
'Since the files lie on different drives, the relative
'filename is same as the Absolute Filename
GetRelativePath = sFile
Exit Function
End If
Base = Split(sBase, "\")
File = Split(sFile, "\")
While Base(I) = File(I)
I = I + 1
Wend
If I = UBound(Base) Then
'Then the Base Path is over, and the file lies
'in a subdirectory of the base directory.
'So simply append the rest of the path.
While I <= UBound(File)
sRel = sRel + File(I) + "\"
I = I + 1
Wend
'Now remove the extra trailing "\" we put earlier.
GetRelativePath = Left(sRel, Len(sRel) - 1)
Exit Function
End If
NewTreeStart = I
'The base path is not yet over, and we need to step
'back using the "..\"
While I < UBound(Base)
sRel = sRel & "..\"
I = I + 1
Wend
While NewTreeStart <= UBound(File)
sRel = sRel & File(NewTreeStart) + "\"
NewTreeStart = NewTreeStart + 1
Wend
'Now remove the extra trailing "\" we put earlier.
GetRelativePath = Left(sRel, Len(sRel) - 1)
End Function
No comments have been posted about Relative Path Function
Gets the relative path of a file w.r.t. a directory. Why not be the first to post a comment about Relative Path Function
Gets the relative path of a file w.r.t. a directory.